/*
Given a binary tree, return the postorder traversal of its nodes' values.

For example:
Given binary tree {1,#,2,3},
   1
    \
     2
    /
   3
return [3,2,1].

Note: Recursive solution is trivial, could you do it iteratively?
*/

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> postorderTraversal(TreeNode *root) {
        vector<int> result;
        if (!root) return result;
        stack<TreeNode *> s_post;
        TreeNode *cur = root;
        do {
            if (cur) {
                if (cur->right)
                    s_post.push(cur->right);
                s_post.push(cur);
                cur = cur->left;
            } else {
                cur = s_post.top();
                s_post.pop();
                if (!s_post.empty() && 
                    cur->right == s_post.top()) {
                    // visit right tree
                    s_post.pop();
                    s_post.push(cur);
                    cur = cur->right;
                } else {
                    // both left and right visited
                    result.push_back(cur->val);
                    cur = NULL;
                }
            }
        } while (cur || !s_post.empty());
        return result;
    }
};
